package com.erps.CommonUtils;

import java.math.BigDecimal;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	public static void setNewCookie(String name, String value, HttpServletResponse response) {
		try {
			Cookie cookie = new Cookie(name, value);
			cookie.setMaxAge(60 * 60 * 24);// 设置24小时生存期，当设置为负值时，则为浏览器进程Cookie(内存中保存)，关闭浏览器就失效。 response.addCookie(cookie);
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
	}

	/**
	 * 获取Cookie值
	 * 
	 * @param name
	 * @param request
	 * @return
	 */
	public static String getCookieValue(String cKeyName, HttpServletRequest request) {
		String value = "";
		try {
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equalsIgnoreCase(cKeyName)) {
					value = cookies[i].getValue();
				}
			}
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
		return value;
	}

	/**
	 * 删除cookie中对应数值
	 * 
	 * @param name
	 * @param request
	 * @param response
	 */
	public static void deleteCookies(String cKeyName, HttpServletRequest request, HttpServletResponse response) {
		try {
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equalsIgnoreCase(cKeyName)) {
					cookies[i].setValue(null);
					cookies[i].setMaxAge(0);// 设置为0为立即删除该Cookie
					response.addCookie(cookies[i]);
				}
			}
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
	}

	/**
	 * 增加规定cookie中的数值
	 * 
	 * @param name
	 * @param value
	 * @param request
	 * @param response
	 */
	public static void addnewCookieValue(String cKeyName, BigDecimal value, HttpServletRequest request, HttpServletResponse response) {
		try {
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {

				if (cookies[i].getName().equalsIgnoreCase(cKeyName)) {
					cookies[i].setValue(new BigDecimal(cookies[i].getValue().trim()).add(value).toString());
					response.addCookie(cookies[i]);
				}
			}
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
	}

	/**
	 * 减去规定cookie中的数值
	 * 
	 * @param name
	 * @param value
	 * @param request
	 * @param response
	 */
	public static void subCookieValue(String cKeyName, BigDecimal value, HttpServletRequest request, HttpServletResponse response) {
		try {
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equalsIgnoreCase(cKeyName)) {
					cookies[i].setValue(new BigDecimal(cookies[i].getValue()).subtract(value).toString());
					response.addCookie(cookies[i]);
				}
			}
		} catch (RuntimeException e) {
			// TODO: handle exception
		}
	}
}
